const UserModule = require('../modules/user')
const TokenModule = require('../modules/token')
const jwt = require('../utils/jwt')
const utils = require('../utils/util')
const qs = require('querystring')

class AuthController {
  /**
   * 用户注册
   * 
   * @param ctx
   */
  static async register(ctx) {

    let req = ctx.request.body
    // 判断用户名是否存在
    let repeat = JSON.stringify(await UserModule.getUserByName(req.name)) === JSON.stringify([])
      ? false
      : true
    if (repeat) {
      ctx.response.status = 200
      ctx.body = {
        code: 412,
        msg: '用户名已存在'
      }
      return
    }
    if (req.name && req.password && req.email) {
      if (!utils.isEmail(req.email)) {
        ctx.response.status = 200
        ctx.body = {
          code: 412,
          msg: '邮箱格式错误',
        }
        return
      } else {
        const user = await UserModule.getUserByEmail(req.email)
        if (user[0]){
          ctx.response.status = 200
          ctx.body = {
            code: 412,
            msg: '邮箱已被使用'
          }
          return
        }
      }
      try {
        req.roles = 'user'
        const ret = await UserModule.register(req)
        const res = await UserModule.getUserByName(ret.name)

        ctx.response.status = 200
        ctx.body = {
          code: 200,
          msg: '注册成功',
          body: {
            id: res[0].id,
            name: res[0].name,
            password: res[0].password,
            email: res[0].email
          }
        }
      } catch (err) {
        console.log(err)
        ctx.response.status = 412
        ctx.body = {
          code: 412,
          msg: '创建失败',
          body: err
        }
      }
    } else {
      ctx.response.status = 200
      ctx.body = {
        code: 416,
        msg: '缺少参数'
      }
    }
  }

  /**
   * 创建管理员
   * @param {*} ctx {name, password} 
   */
  static async addAdmin(ctx) {
    let data = ctx.request.body
    let repeat = JSON.stringify(await UserModule.getUserByName(data.name)) === JSON.stringify([])
      ? false
      : true
    if (repeat) {
      ctx.response.status = 200
      ctx.body = {
        code: 412,
        msg: '用户名已存在'
      }
      return
    }
    if (data.name && data.password && data.roles) {
      try {
        data.email = ''
        data.avatarURL = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
        const ret = await UserModule.register(data)
        const res = await UserModule.getAdminByName(ret.name)

        ctx.response.status = 200
        ctx.body = {
          code: 200,
          msg: '注册成功',
          body: {
            id: res[0].id,
            name: res[0].name,
            password: res[0].password,
          }
        }
      } catch (err) {
        console.log(err)
        ctx.response.status = 412
        ctx.body = {
          code: 412,
          msg: '创建失败',
        }
      }
    } else {
      ctx.response.status = 200
      ctx.body = {
        code: 416,
        msg: '缺少参数'
      }
    }
  }

  /**
   * 用户登录
   * 
   * @param ctx
   */
  static async login(ctx) {

    const req = qs.parse(ctx.request.url.split('?')[1])
    if (req.name && req.password) {
      try {
        let isEmail = utils.isEmail(req.name)
        const userInfo = isEmail
          ? await UserModule.getUserByEmail(req.name)
          : await UserModule.getUserByName(req.name)
        const serverInfo = userInfo[0] ? userInfo[0] : {}
        const hasUser = userInfo.length ? true : false
        
        if (!hasUser) {
          ctx.response.status = 200
          ctx.body = {
            code: 20001,
            msg: '账户或邮箱不存在'
          }
          return
        } else if (serverInfo.password !== req.password) {
          ctx.response.status = 200
          ctx.body = {
            code: 20001,
            msg: '密码错误'
          }
          return
        }

        req.name = serverInfo.name
        req.roles = 'user'
        const ret = await TokenModule.createToken(req)

        ctx.response.status = 200
        ctx.body = {
          code: 200,
          msg: '登录成功',
          body: {
            'token': ret.token
          }
        }
      } catch (err) {
        console.log(err)
        ctx.response.status = 401
        ctx.body = err
      }
    } else {
      ctx.response.status = 416
      ctx.body = {
        code: 200,
        msg: '缺少参数'
      }
    }
  }

  /**
   * 管理员登录
   * 
   * @param {*} ctx 
   */
  static async adminLogin(ctx) {
    let req = ctx.request.body
    if (!req.name || !req.password) {
      ctx.body = {
        code: 416,
        msg: '缺少参数'
      }
      return
    }
    let admin = await UserModule.getAdminByName(req.name)
    if (!admin.length) {
      ctx.body = {
        code: 40000,
        msg: '账号不存在'
      }
      return
    } else if (admin[0].password !== req.password) {
      ctx.body = {
        code: 40000,
        msg: '密码错误'
      }
      return
    } else {
      let info = { name: admin[0].name, password: admin[0].password, roles: admin[0].roles }
      let token = await TokenModule.createToken(info)
      ctx.body = {
        code: 200,
        data: {
          token: token.token
        }
      }
    }
  }

  /**
   * 管理员登出
   * 
   * @param {*} ctx 
   */
  static async adminLogout(ctx) {
    const req = ctx.request.body
    console.log(req)
    try {
      await TokenModule.destroyTokenByToken(req.token)
      ctx.body = {
        code: 200,
        msg: 'success'
      }
    } catch(err) {
      console.log(err)
      ctx.body = {
        code: 400,
        msg: 'error'
      }
    }
  }
  
  /**
   * token验证
   * 
   * @param ctx
   */
  static async tokenVerify(ctx) {
    
    const token = ctx.request.header.authorization ? ctx.request.header.authorization.split(' ')[1] : false

    token || (() => {
      ctx.response.status = 416
      ctx.body = {
        code: 20002,
        msg: '无token'
      }
      return
    })()

    try {
      const tokenInfo = jwt.verifyToken(token)
      const localToken = await TokenModule.getTokenByName(tokenInfo.name)

      if (localToken.length && localToken.filter(item => {
        return item.token === token
      })) {

        ctx.response.status = 200
        ctx.body = {
          code: 200,
          msg: '验证成功',
          data: tokenInfo
        }
      } else {
        ctx.response.status = 200,
        ctx.body = {
          code: 20002,
          msg: '无效token'
        }
      }
    } catch (err) {
      console.log(err)
      ctx.response.status = 416
      ctx.body = {
        code: 20002,
        body: err
      }
    }
  }
}

module.exports = AuthController
